package com.hzhk.happyrent.ui.activity.personal;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.google.gson.Gson;
import com.hzhk.happyrent.Constants;
import com.hzhk.happyrent.R;
import com.hzhk.happyrent.bean.CodeModel;
import com.hzhk.happyrent.bean.person.PersonInfoModel;
import com.hzhk.happyrent.bean.person.UploadBitmapModel;
import com.hzhk.happyrent.network.API;
import com.hzhk.happyrent.network.HttpManager;
import com.hzhk.happyrent.network.MyStringResponse;
import com.hzhk.happyrent.ui.view.ClearEditText;
import com.hzhk.happyrent.utils.MyPerference;
import com.hzhk.happyrent.utils.SystemUtils;
import com.hzhk.happyrent.utils.glide.ShowImageUtils;
import com.hzhk.happyrent.utils.idcheck.IDCodeInfo;
import com.hzhk.happyrent.utils.idcheck.IDValidator;
import com.tamic.novate.Throwable;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class PersonInfoActivity extends AppCompatActivity {

    private static final int RESULT_LOAD_IMAGE =0;
    public static final int RESULT_CAMERA_IMAGE=1;
    @BindView(R.id.activity_titlebar_left)
    ImageView activityTitlebarLeft;
    @BindView(R.id.activity_titlebar_center)
    TextView activityTitlebarCenter;
    @BindView(R.id.activity_titlebar_right)
    ImageView activityTitlebarRight;
    @BindView(R.id.act_user_name)
    ClearEditText actUserName;
    @BindView(R.id.choose_student)
    TextView chooseStudent;
    @BindView(R.id.choose_job)
    TextView chooseJob;
    @BindView(R.id.act_user_school)
    ClearEditText actUserSchool;
    @BindView(R.id.act_user_phone)
    ClearEditText actUserPhone;
    @BindView(R.id.card_report)
    ImageView cardReport;
    @BindView(R.id.card_back)
    ImageView cardBack;
    @BindView(R.id.act_login_submit)
    Button actLoginSubmit;
    @BindView(R.id.l_card_report)
    LinearLayout lCardReport;
    @BindView(R.id.l_card_back)
    LinearLayout lCardBack;

    String name;
    String nameJobOrSchool;
    String personId;
    int index = 1;
    int card_type=0;
    @BindView(R.id.school_or_company)
    TextView schoolOrCompany;

    private String bitmapReport;
    private String bitmapBack;
    private PopupWindow popupWindow;
    private View popView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_person_info);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        activityTitlebarLeft.setImageResource(R.drawable.back);
        activityTitlebarCenter.setText(R.string.person_info);
        activityTitlebarRight.setVisibility(View.GONE);
        if(!TextUtils.isEmpty(MyPerference.getInstance().getUserId())){
            getPersonInfo();
        }
    }

    private void getPersonInfo() {
        Map<String,Object> params=new HashMap<>();
        params.put(Constants.USER_ID,MyPerference.getInstance().getUserId());
        HttpManager.getInstance().get(API.GET_USER_IDENTITY, params, new MyStringResponse(this) {
            @Override
            public void onError(Object tag, Throwable e) {

            }

            @Override
            public void onCancel(Object tag, Throwable e) {

            }

            @Override
            public void onNext(Object tag, String response) {
                try{
                    PersonInfoModel baseModel=new Gson().fromJson(response,PersonInfoModel.class);
                    if(baseModel.getData()!=null&&baseModel.getData().getUser_identity()!=null){
                        actUserName.setText(baseModel.getData().getUser_identity().getReal_name());
                        if("1".equals(baseModel.getData().getUser_identity().getRole())){
                            chooseMessage(1);
                            actUserSchool.setText(baseModel.getData().getUser_identity().getSchool_name());
                        }else{
                            chooseMessage(2);
                            actUserSchool.setText(baseModel.getData().getUser_identity().getCompany_name());
                        }
                        actUserPhone.setText(baseModel.getData().getUser_identity().getCredit_card());
                        bitmapReport=baseModel.getData().getUser_identity().getCredit_card_font_pic();
                        bitmapBack=baseModel.getData().getUser_identity().getCredit_card_behind_pic();
                        ShowImageUtils.showImageView(PersonInfoActivity.this,cardReport,baseModel.getData().getUser_identity().getCredit_card_font_pic());
                        ShowImageUtils.showImageView(PersonInfoActivity.this,cardBack,baseModel.getData().getUser_identity().getCredit_card_behind_pic());
                        if("0".equals(baseModel.getData().getUser_identity().getCheck())){
                            actUserName.setFocusable(false);
                            actUserName.setFocusableInTouchMode(false);
                            actUserSchool.setFocusable(false);
                            actUserSchool.setFocusableInTouchMode(false);
                            actUserPhone.setFocusable(false);
                            actUserPhone.setFocusableInTouchMode(false);
                            cardReport.setClickable(false);
                            cardBack.setClickable(false);
                            actLoginSubmit.setText(R.string.info_checking);
                            actLoginSubmit.setClickable(false);
                        }else if("1".equals(baseModel.getData().getUser_identity().getCheck())){
                            actUserName.setFocusable(false);
                            actUserName.setFocusableInTouchMode(false);
                            actUserSchool.setFocusable(false);
                            actUserSchool.setFocusableInTouchMode(false);
                            actUserPhone.setFocusable(false);
                            actUserPhone.setFocusableInTouchMode(false);
                            cardReport.setClickable(false);
                            cardBack.setClickable(false);
                            actLoginSubmit.setText(R.string.message_pass);
                            actLoginSubmit.setClickable(false);
                        }else if("2".equals(baseModel.getData().getUser_identity().getCheck())){
                            Toast.makeText(PersonInfoActivity.this, R.string.message_change_reminder, Toast.LENGTH_SHORT).show();
                            actLoginSubmit.setText(R.string.message_change);
                        }
                    }
                }catch (Exception e){

                }
            }
        });
    }
    private void getText() {
        name = actUserName.getText().toString();
        nameJobOrSchool = actUserSchool.getText().toString();
        personId = actUserPhone.getText().toString();
    }

    @OnClick({R.id.activity_titlebar_left, R.id.choose_student
            , R.id.choose_job, R.id.card_report
            , R.id.card_back, R.id.act_login_submit
            , R.id.l_card_report, R.id.l_card_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.activity_titlebar_left:
                finish();
                break;
            case R.id.choose_student:
                chooseMessage(1);
                break;
            case R.id.choose_job:
                chooseMessage(2);
                break;
            case R.id.card_report:
                if(verifyStoragePermissions(this)){
                    card_type=0;
                    if(popupWindow==null){
                        showPopueWindow();
                    }
                    shootBottom();
                }else{
                    Toast.makeText(this, "请允许授权", Toast.LENGTH_SHORT).show();
                }

                break;
            case R.id.card_back:
                if(verifyStoragePermissions(this)){
                    card_type=1;
                    if(popupWindow==null){
                        showPopueWindow();
                    }
                    shootBottom();
                }else{
                    Toast.makeText(this, "请允许授权", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.act_login_submit:
                postData();
                break;
            case R.id.l_card_report:
                break;
            case R.id.l_card_back:
                break;
        }
    }
    private void chooseMessage(int i){
        if(i==1&&index != i){
            index = i;
            initTextData();
            chooseStudent.setCompoundDrawablesWithIntrinsicBounds(null, null, getResources().getDrawable(R.drawable.type_selected), null);
            chooseJob.setCompoundDrawablesWithIntrinsicBounds(null, null, getResources().getDrawable(R.drawable.type), null);
        }else if(i==2&&index != i){
            index = i;
            initTextData();
            chooseStudent.setCompoundDrawablesWithIntrinsicBounds(null, null, getResources().getDrawable(R.drawable.type), null);
            chooseJob.setCompoundDrawablesWithIntrinsicBounds(null, null, getResources().getDrawable(R.drawable.type_selected), null);
        }
    }

    private void initTextData() {
        if (index == 1) {
            actUserSchool.setHint(R.string.hint_account_school);
            schoolOrCompany.setText(R.string.name_school);
        } else {
            actUserSchool.setHint(R.string.hint_account_company);
            schoolOrCompany.setText(R.string.name_company);
        }
    }

    private void postData() {
        getText();
        if (TextUtils.isEmpty(name)) {
            Toast.makeText(this, R.string.name_true, Toast.LENGTH_SHORT).show();
        } else if (TextUtils.isEmpty(nameJobOrSchool)) {
            if (index == 1) {
                Toast.makeText(this, R.string.hint_account_school, Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, R.string.hint_account_company, Toast.LENGTH_SHORT).show();
            }
        } else if (TextUtils.isEmpty(personId)) {
            Toast.makeText(this, R.string.num_person, Toast.LENGTH_SHORT).show();
        } else if (!new IDValidator().isValid(personId)) {
            Toast.makeText(this, R.string.num_error, Toast.LENGTH_SHORT).show();
        } else if (cardReport.getDrawable()==null){
            Toast.makeText(this, R.string.card_report, Toast.LENGTH_SHORT).show();
        } else if (cardBack.getDrawable()==null){
            Toast.makeText(this, R.string.card_back, Toast.LENGTH_SHORT).show();
        } else {
//            IDCodeInfo info = new IDValidator().getInfo(personId);
//            Toast.makeText(this, info.toString(), Toast.LENGTH_SHORT).show();
//            MyPerference.getInstance().setPersonInfo("");
            initData();
        }
    }
    private void postBitmap(Bitmap bitmap, final int index){
        Map<String,Object> params=new HashMap<>();
        params.put("data", SystemUtils.bitmapToBase64(bitmap));
        params.put("filename", generateFileName()+".jpg");
        HttpManager.getInstance().perform_post(API.UPLOAD, params, new MyStringResponse(this) {
            @Override
            public void onError(Object tag, Throwable e) {
//                Toast.makeText(PersonInfoActivity.this,e.getMessage(),Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancel(Object tag, Throwable e) {

            }

            @Override
            public void onNext(Object tag, String response) {
                UploadBitmapModel uploadBitmapModel=new Gson().fromJson(response,UploadBitmapModel.class);
                if(index==0){
                    bitmapReport=uploadBitmapModel.getData().getObject_url();
                }else{
                    bitmapBack=uploadBitmapModel.getData().getObject_url();
                }
            }
        });
    }

    private void initData() {
        Map<String,Object> params=new HashMap<>();
        params.put("user_id", MyPerference.getInstance().getUserId());
        params.put("real_name", name);
        params.put("role", index+"");
        if(index==1){
            params.put("school_name", nameJobOrSchool);
        }else{
            params.put("company_name", nameJobOrSchool);
        }
        params.put("credit_card", personId);
        params.put("credit_card_font_pic", bitmapReport);
        params.put("credit_card_behind_pic", bitmapBack);

        HttpManager.getInstance().perform_post(API.POST_USER_INFO, params, new MyStringResponse(this) {
            @Override
            public void onError(Object tag, Throwable e) {

            }

            @Override
            public void onCancel(Object tag, Throwable e) {

            }

            @Override
            public void onNext(Object tag, String response) {
                CodeModel codeModel=new Gson().fromJson(response,CodeModel.class);
                if (codeModel.getErrCode()==0){
//                    PersonInfoModel baseModel=new Gson().fromJson(response,PersonInfoModel.class);
                    MyPerference.getInstance().setPersonInfo(response);
                    Toast.makeText(PersonInfoActivity.this, "提交信息成功", Toast.LENGTH_SHORT).show();
                    finish();
                }else {
                    Toast.makeText(PersonInfoActivity.this, codeModel.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void showPopueWindow(){
        popView = View.inflate(this, R.layout.picture_get,null);
        Button bt_album = (Button) popView.findViewById(R.id.btn_pop_album);
        Button bt_camera = (Button) popView.findViewById(R.id.btn_pop_camera);
        Button bt_cancle = (Button) popView.findViewById(R.id.btn_pop_cancel);
        //获取屏幕宽高
        int weight = getResources().getDisplayMetrics().widthPixels;
        int height = getResources().getDisplayMetrics().heightPixels*1/3;

        popupWindow = new PopupWindow(popView,weight,height);
        popupWindow.setAnimationStyle(R.style.dialog);
        popupWindow.setFocusable(true);
        //点击外部popueWindow消失
        popupWindow.setOutsideTouchable(true);

        bt_album.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(i, RESULT_LOAD_IMAGE);
                popupWindow.dismiss();

            }
        });
        bt_camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                takeCamera(RESULT_CAMERA_IMAGE);
                popupWindow.dismiss();

            }
        });
        bt_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();

            }
        });
        //popupWindow消失屏幕变为不透明
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1.0f;
                getWindow().setAttributes(lp);
            }
        });
    }
    private void shootBottom(){
        //popupWindow出现屏幕变为半透明
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.5f;
        getWindow().setAttributes(lp);
        popupWindow.showAtLocation(popView, Gravity.BOTTOM, 0, 50);
        TranslateAnimation animation = new TranslateAnimation(
                Animation.RELATIVE_TO_SELF, 0,
                Animation.RELATIVE_TO_SELF, 0,
                Animation.RELATIVE_TO_SELF, 1f,
                Animation.RELATIVE_TO_SELF, 0);
        animation.setDuration(150);
        popView.startAnimation(animation);
    }

    public static Bitmap getSmallBitmap(String filePath) {
        Bitmap bitmap = null;
        try {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;//只解析图片边沿，获取宽高
            BitmapFactory.decodeFile(filePath, options);
            // 计算缩放比
            options.inSampleSize = calculateInSampleSize(options, 480, 800);
            // 完整解析图片返回bitmap
            options.inJustDecodeBounds = false;
            bitmap=BitmapFactory.decodeFile(filePath, options);
        }catch (Exception e){
            e.printStackTrace();
        }
        return bitmap;
    }

    public static int calculateInSampleSize(BitmapFactory.Options options,
                                            int reqWidth, int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
        if (height > reqHeight || width > reqWidth) {
            final int heightRatio = Math.round((float) height / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }
        return inSampleSize;
    }
    private void takeCamera(int num) {

        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // Ensure that there's a camera activity to handle the intent
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            // Create the File where the photo should go
            File photoFile = null;
            photoFile =createImgFile();
            // Continue only if the File was successfully created
            if (photoFile != null) {
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                        Uri.fromFile(photoFile));
            }
        }
        startActivityForResult(takePictureIntent, num);//跳转界面传回拍照所得数据
    }
    private String mCurrentPhotoPath;
    private File createImgFile(){
        //确定文件名
        String fileName="img_"+new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date())+".jpg";
//        File dir=getExternalFilesDir(Environment.DIRECTORY_PICTURES);
//        File dir=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
//        File dir=Environment.getExternalStorageDirectory();
        File dir;
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            dir=Environment.getExternalStorageDirectory();
        }else{
            dir=getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        }
        File tempFile=new File(dir,fileName);
        try{
            if(tempFile.exists()){
                tempFile.delete();
            }
            tempFile.createNewFile();
        }catch (IOException e){
            e.printStackTrace();
        }
        //获取文件路径
        mCurrentPhotoPath=tempFile.getAbsolutePath();
        return tempFile;
    }

    public static String generateFileName() {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        return imageFileName;
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK ) {

            if (requestCode == RESULT_LOAD_IMAGE && null != data) {
                Uri selectedImage = data.getData();
                String[] filePathColumn = {MediaStore.Images.Media.DATA};

                Cursor cursor = getContentResolver().query(selectedImage,
                        filePathColumn, null, null, null);
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                final String picturePath = cursor.getString(columnIndex);
//                BitmapFactory.decodeFile(picturePath);
                Bitmap bmp= getSmallBitmap(picturePath);
                if(bmp!=null){
                    if(card_type==0){
                        cardReport.setImageBitmap(bmp);
                    }else{
                        cardBack.setImageBitmap(bmp);
                    }
                    postBitmap(bmp,card_type);
                }
                cursor.close();
            }else if (requestCode == RESULT_CAMERA_IMAGE){

                SimpleTarget target = new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
//                        saveMyBitmap(resource).getAbsolutePath();
                        if(resource!=null) {
                            if (card_type == 0) {
                                cardReport.setImageBitmap(resource);
                            } else {
                                cardBack.setImageBitmap(resource);
                            }
                            postBitmap(resource, card_type);
                        }
                    }

                    @Override
                    public void onLoadStarted(Drawable placeholder) {
                        super.onLoadStarted(placeholder);

                    }

                    @Override
                    public void onLoadFailed(Exception e, Drawable errorDrawable) {
                        super.onLoadFailed(e, errorDrawable);

                    }
                };

                Glide.with(this).load(mCurrentPhotoPath)
                        .asBitmap()
                        .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                        .override(480, 800)//图片压缩
                        .centerCrop()
                        .dontAnimate()
                        .into(target);
            }
        }
    }
    private static final String[] PERMISSION_EXTERNAL_STORAGE = new String[] {
            Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
    private static final int REQUEST_EXTERNAL_STORAGE = 100;
    private boolean verifyStoragePermissions(Activity activity) {

        for (String s : PERMISSION_EXTERNAL_STORAGE) {
            int permissionWrite = ActivityCompat.checkSelfPermission(activity,
                    s);
            if(permissionWrite != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(activity, PERMISSION_EXTERNAL_STORAGE,
                        REQUEST_EXTERNAL_STORAGE);
                return false;
            }
        }
        return true;
    }
}
